<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Widgets in Tkinter</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, Widgets, Tkinter, Python, programming, Linux">
<meta name="description" content="This part of the Tkinter tutorial covers Tkinter widgets.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Widgets</h1>

<p>
In this part of the Tkinter tutorial, we will cover
some basic Tkinter widgets.  
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
Widgets are basic building blocks of a GUI application. Over the years, 
several widgets became a standard in all toolkits on all OS platforms. 
For example a button, a check box or a scroll bar. Some of them might have
a different name. For instance, a check box is called a check button in Tkinter.
Tkinter has a small set of widgets which cover the basic programming needs.
More specialized components can be created as custom widgets. 
</p>


<h2>Checkbutton</h2>

<p>
The <code>Checkbutton</code> is a widget, that has two states. On and Off. 
The On state is visualized by a check mark. It is used to denote some boolean property. 
The <code>Checkbutton</code> widget provides a check box with a text label.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

This program toggles the title of the
window with the Checkbutton widget

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""


from Tkinter import Tk, Frame, Checkbutton
from Tkinter import IntVar, BOTH


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Checkbutton")

        self.pack(fill=BOTH, expand=1)
        self.var = IntVar()
        
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=50)


    def onClick(self):
       
        if self.var.get() == 1:
            self.master.title("Checkbutton")
        else:
            self.master.title("")


def main():
  
    root = Tk()
    root.geometry("250x150+300+300")
    app = Example(root)
    root.mainloop()  


if __name__ == '__main__':
    main()  
 
</pre>

<p>
In our example, we place a check button on the window. The check 
button shows/hides the title of the window. 
</p>

<pre class="explanation">
self.var = IntVar()
</pre>

<p>
We create an <code>IntVar</code> object. It is a value holder for integer
values for widgets in Tkinter.
</p>

<pre class="explanation">
cb = Checkbutton(self, text="Show title",
    variable=self.var, command=self.onClick)
</pre>

<p>
An instance of the <code>Checkbutton</code> is created. The value holder
is connected to the widget via the <code>variable</code> parameter. When
we click on the check button, the onClick() method is called. This is
done with the <code>command</code> parameter. 
</p>


<pre class="explanation">
cb.select()
</pre>

<p>
Initially, the title is shown in the titlebar. So at the start, we make it
checked with the <code>select()</code> method.
</p>

<pre class="explanation">
if self.var.get() == 1:
    self.master.title("Checkbutton")
else:
    self.master.title("")
</pre>

<p>
Inside the onClick() method, we display or hide the title based on
the value from the self.var variable. 
</p>


<img src="/img/gui/tkinter/checkbutton.png" alt="Checkbutton">
<div class="figure">Figure: Checkbutton</div>


<h2>Label</h2>

<p>
The <code>Label</code> widget is used to display text or images.
No user interaction is available.
</p>

<pre>
sudo apt-get install python-imaging-tk
</pre>

<p>
In order to run this example, we must install python-imaging-tk
module. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this script, we use the Label
widget to show an image.

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""


from PIL import Image, ImageTk
from Tkinter import Tk, Frame, Label


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Label")

        self.img = Image.open("tatras.jpg")
        tatras = ImageTk.PhotoImage(self.img)
        label = Label(self, image=tatras)

        label.image = tatras
        label.pack()

        self.pack()
        
    def setGeometry(self):
      
        w, h = self.img.size
        self.parent.geometry(("%dx%d+300+300") % (w, h))
        

def main():
  
    root = Tk()
    ex = Example(root)
    ex.setGeometry()
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
Our example shows an image on the window.
</p>

<pre class="explanation">
from PIL import Image, ImageTk
</pre>

<p>
By default, the <code>Label</code> widget can display only a limited
set of image types. To display a jpg image, we must use the PIL, Python
Imaging Library module. 
</p>

<pre class="explanation">
self.img = Image.open("tatras.jpg")
tatras = ImageTk.PhotoImage(self.img)
</pre>

<p>
We create an image from the image file in the current working directory.
Later we create a photo image from the image. 
</p>

<pre class="explanation">
label = Label(self, image=tatras)
</pre>

<p>
The photoimage is given to the <code>image</code> parameter of the 
label widget. 
</p>

<pre class="explanation">
label.image = tatras
</pre>

<p>
In order not to be garbage collected, the image reference must be
stored.
</p>

<pre class="explanation">
w, h = self.img.size
self.parent.geometry(("%dx%d+300+300") % (w, h))
</pre>

<p>
We make the size of the window to exactly fit the image size. 
</p>


<h2>Scale</h2>

<p>
<code>Scale</code> is a widget that lets the user 
graphically select a value by sliding a knob within 
a bounded interval. Our example will show a selected number
in a label widget. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this script, we show how to
use the Scale widget.

author: Jan Bodnar
last modified: December 2010
website: www.zetcode.com
"""

from ttk import Frame, Label, Scale, Style
from Tkinter import Tk, BOTH, IntVar


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Scale")
        self.style = Style()
        self.style.theme_use("default")        
        
        self.pack(fill=BOTH, expand=1)

        scale = Scale(self, from_=0, to=100, 
            command=self.onScale)
        scale.place(x=20, y=20)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=130, y=70)

    def onScale(self, val):
     
        v = int(float(val))
        self.var.set(v)
         

def main():
  
    root = Tk()
    ex = Example(root)
    root.geometry("300x150+300+300")
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
We have two widgets in the above script. A scale and a label.
A value from the scale widget is shown in the label widget. 
</p>

<pre class="explanation">
scale = Scale(self, from_=0, to=100, 
    command=self.onScale)
</pre>

<p>
<code>Scale</code> widget is created. We provide the lower and upper
bounds. The from is a regular Python keyword, that is why there is an
underscore after the first parameter. When we move the knob of the scale,
the onScale() method is called. 
</p>

<pre class="explanation">
self.var = IntVar()
self.label = Label(self, text=0, textvariable=self.var)    
</pre>

<p>
An integer value holder and label widget are created. Value from the holder
is shown in the label widget. 
</p>

<pre class="explanation">
def onScale(self, val):
  
    v = int(float(val))
    self.var.set(v)
</pre>

<p>
The onScale() method receives a currently selected value from the 
scale widget as a parameter. The value is first converted to a float
and then to integer. Finally, the value is set to the value holder of the
label widget. 
</p>


<img src="/img/gui/tkinter/scale.png" alt="Scale">
<div class="figure">Figure: Scale</div>


<h2>Listbox</h2>


<p>
<code>Listbox</code> is a widget that displays a list of objects. It allows the user 
to select one or more items.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial

In this script, we show how to
use the Listbox widget.

author: Jan Bodar
last modified: December 2010
website: www.zetcode.com
"""

from ttk import Frame, Label, Style
from Tkinter import Tk, BOTH, Listbox, StringVar, END


class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
            
        lb.bind("&lt;&lt;ListboxSelect&gt;&gt;", self.onSelect)    
            
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=210)

    def onSelect(self, val):
      
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)   

        self.var.set(value)
         

def main():
  
    root = Tk()
    ex = Example(root)
    root.geometry("300x250+300+300")
    root.mainloop()  


if __name__ == '__main__':
    main()  
</pre>

<p>
In our example, we show a list of actresses in the <code>Listbox</code>. 
The currently selected actress is displayed in a label widget. 
</p>

<pre class="explanation">
acts = ['Scarlett Johansson', 'Rachel Weiss', 
    'Natalie Portman', 'Jessica Alba']
</pre>

<p>
This is a list of actresses to be shown in the listbox. 
</p>

<pre class="explanation">
lb = Listbox(self)
for i in acts:
    lb.insert(END, i)
</pre>

<p>
We create an instance of the <code>Listbox</code> and insert all
the items from the above mentioned list.
</p>

<pre class="explanation">
lb.bind("&lt;&lt;ListboxSelect&gt;&gt;", self.onSelect)    
</pre>

<p>
When we select an item in the listbox, the &lt;&lt;ListboxSelect&gt;&gt;
event is generated. We bind the onSelect() method to this event. 
</p>


<pre class="explanation">
self.var = StringVar()
self.label = Label(self, text=0, textvariable=self.var)  
</pre>

<p>
A label and its value holder is created. In this label we will display
the currently selected item. 
</p>

<pre class="explanation">
sender = val.widget
</pre>

<p>
We get the sender of the event. It is our listbox widget.
</p>


<pre class="explanation">
idx = sender.curselection()
</pre>

<p>
We find out the index of the selected item using the 
<code>curselection()</code> method. 
</p>

<pre class="explanation">
value = sender.get(idx)  
</pre>

<p>
The actual value is retrieved with the <code>get()</code> method,
which takes the index of the item. 
</p>


<pre class="explanation">
self.var.set(value)
</pre>

<p>
Finally, the label is updated. 
</p>


<img src="/img/gui/tkinter/listbox.png" alt="Listbox widget">
<div class="figure">Figure: Listbox widget</div>

<p>
In this part of the Tkinter tutorial, we have presented several Tkinter widgets.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 8, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

